package cn.stylefeng.guns.modular.system.controller.webController;

import cn.stylefeng.guns.core.util.TencentCloudUtils;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:    UploadFileController
 * Package:    cn.stylefeng.guns.modular.system.controller.webController
 * Description:
 * Datetime:    2020/8/11   13:37
 */
@Api(value = "文件上传接口", tags = "UploadFileController", description = "文件上传接口")
@AllArgsConstructor
@RestController
@RequestMapping("/api/upload/")
public class UploadFileController extends BaseController{

    final private String TEMPPREFIX = "temp/";
    /**
     * 上传图片
     */
    @ApiOperation(value = "上传文件", notes="上传文件到腾讯云")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "prefix", value = "文件存放位置", paramType = "query")
    })
    @RequestMapping(value = "/uploadFile",method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ResponseData upload(@ApiParam(value = "文件", required = true) @RequestParam(value = "file") MultipartFile file,
                               @RequestParam(value = "prefix",required = false) String prefix) {
        try {
            Boolean result = TencentCloudUtils.checkPic(file);
            if (!result) {
                return ResponseData.error(407, "所选图片违规！");
            }
            Map<String, String> resultMap = TencentCloudUtils.uploadFile(file,
                    ToolUtil.isEmpty(prefix)?TEMPPREFIX:prefix);
            return ResponseData.success(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.error("服务器异常");
        }
    }

    /**
     * 删除图片
     *
     * @param fileName
     * @return
     */
    @ApiOperation(value = "删除文件", notes="删除文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "文件名", paramType = "query",required = true)
    })
    @RequestMapping(value = "deleteFile",method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ResponseData deleteImage(@RequestParam(value = "fileName") String fileName) {
        if (ToolUtil.isEmpty(fileName)){
            return ResponseData.error("参数为null!");
        }
        TencentCloudUtils.deleteObject(fileName);
        return SUCCESS_TIP;
    }

}
